﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;

namespace Cordyceps.Demo.SqlServer.DbMigrator.EFCore;

public class DemoMigrationsDbContextFactory : IDesignTimeDbContextFactory<DemoMigrationsDbContext>
{
    public DemoMigrationsDbContext CreateDbContext(string[] args)
    {
        // 构建配置。这里假设迁移器项目（最终运行工具的项目）的appsettings.json是配置源
        var configuration = BuildConfiguration();
        var connectionString = configuration.GetConnectionString("Default");
        // 配置DbContext选项
        var optionsBuilder = new DbContextOptionsBuilder<DemoMigrationsDbContext>()
            .UseSqlServer(configuration.GetConnectionString("Default")); // 根据你的数据库调整

        return new DemoMigrationsDbContext(optionsBuilder.Options);
    }

    private static IConfigurationRoot BuildConfiguration()
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory()) // 指向迁移器项目的目录
            .AddJsonFile("appsettings.json", false)
            .AddJsonFile("appsettings.Development.json", true);

        return builder.Build();
    }
}